﻿#region Using

using System;
using System.Collections.Generic;
using System.Linq;

using Common.Base;

using CommunicationLibrary;

using ServerApplication.Enums;
using ServerApplication.Interfaces;

#endregion

namespace ServerApplication.Networking
{
    public class PlayerManager : IPlayerManager, IClientManager
    {
        private readonly Dictionary<IClient, ServerPlayer> networkDictonary = new Dictionary<IClient, ServerPlayer>();

        public IClient FindClient(Identifiable identifiable)
        {
            lock (this.networkDictonary)
            {
                var player = this.networkDictonary.Values.FirstOrDefault(x => x.Equals(identifiable));

                if (player == null || player.ServerPlayerState == ServerPlayerState.Disconnected)
                {
                    return EmptyClient.Instance;
                }

                return this.networkDictonary.First(x => x.Value.Equals(player)).Key;
            }
        }

        public bool TryFindPlayer(IClient client, out ServerPlayer player)
        {
            lock (this.networkDictonary)
            {
                if (!this.networkDictonary.ContainsKey(client))
                {
                    player = null;
                    return false;
                }

                player = this.networkDictonary[client];
                return true;
            }
        }

        public bool TryGeneratePlayer(IClient client, string name, out ServerPlayer player)
        {
            lock (this.networkDictonary)
            {
                if (this.networkDictonary.ContainsKey(client))
                {
                    player = null;
                    return false;
                }

                player = new ServerPlayer(name);
                player.Disconnected += this.RemoveOnDisconnect;
                this.networkDictonary.Add(client, player);
                return true;
            }
        }

        private void RemoveOnDisconnect(object sender, EventArgs e)
        {
            var player = sender as ServerPlayer;

            lock (this.networkDictonary)
            {
                var client = this.networkDictonary.FirstOrDefault(x => x.Value.Equals(player)).Key;

                if (client != null)
                {
                    this.networkDictonary.Remove(client);
                }
            }
        }
    }
}